<template>
    <el-form class="login-container" ref="loginForm" :rules="rules" :model="loginModel"
             v-loading="loading">
        <h1>管理系统登录</h1>
        <span>Shopping,Let's Go!</span>
        <el-form-item label="账户" prop="name">
            <el-input placeholder="请输入账号" v-model="loginModel.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input placeholder="请输入密码" type="password" v-model="loginModel.password"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button @click="login('loginForm')" class="login-btn" type="primary">登 录</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
    import {loginApi} from "../api/userApi";
    import {setToken} from "../utils/auth";

    export default {
        name: 'Login',
        components: {},
        data() {
            return {
                loading: false,
                loginModel: {
                    name: '',
                    password: ''
                },
                rules: {
                    name: [{required: true, message: "请输入账号", trigger: 'blur'}],
                    password: [{required: true, message: "请输入密码", trigger: 'blur'}],
                }
            }
        },
        methods: {
            login(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        loginApi(this.loginModel.name, this.loginModel.password).then((res) => {
                            this.loading = false;
                            console.log(res.status)
                            if (res.status === 0) {
                                this.$store.commit('setToken', res.data);
                                setToken(res.data)
                                this.$router.replace('/dashboard');
                            } else {
                                this.$message.error('登录失败：' + res.msg);
                            }
                        }).catch(() => {
                            this.loading = false
                        });
                    }
                });
            }
        }
    }
</script>

<style scoped lang="stylus">
    .login-container {
        width: 300px;
        /*水平垂直居中，vh表示视口大小*/
        margin: 20vh auto;
        border-radius: 8px;
        border: 1px solid #ccc;
        background-color: #fff;
        padding: 35px 35px 15px 35px;

        .login-btn {
            width: 100%;
        }
    }
</style>
